﻿/// <reference path="../Libriries/jquery-2.0.3.js" />
/// <reference path="../Libriries/q.js" />
/// <reference path="class.js" />

var CoursesMaker = (function () {
    var COURSES_DEFAULT_PATH = "../Resources/XmlRes/programming-courses.xml";

    var courses = [];

    var Course = Class.create({
        init: function (name, lectures) {
            this.name = name;
            this.lectures = lectures;

            this.frame = $("<div class='course'></div>");
            this.anchor = $("<a href='#'></a>");
            this.anchor.text(name);

            this.frame.append(this.anchor);
        },
        render: function () {
            return this.frame;
        }
    });

    var loadCourses = function (selector, lecturesSelector) {
        var holder = $(selector);
        var fragment = document.createDocumentFragment();

        $.ajax({
            type: 'GET',
            url: COURSES_DEFAULT_PATH,
            dataType: 'xml',
            success: function (xml) {
                $(xml).find("course").each(function () {
                    var name = $(this).text();
                    var course = new Course(name);
                    course.lectures = $(this).attr("lectures");

                    var selected = $(this).attr("selected");
                    if (selected) {
                        course.frame.addClass("selected");
                        LecturesMaker.makeLectures(lecturesSelector, course.name, course.lectures);
                    }

                    courses.push(course);

                    $(fragment).append(course.render());
                    course.frame.fadeIn(300);

                    course.frame.click(function (event) {
                        LecturesMaker.makeLectures(lecturesSelector, course.name, course.lectures);
                    });
                });

                holder.html(null);
                holder.append(fragment);
            },
            error: function (error) {
                holder.append("<span style='color: white;'> There was an error loading courses."
                    + " Please contact an administrator</span>");
            }
        });
    }

    return {
        makeCourses: loadCourses
    }
}());